/**
 *  @file SDLApplication.cpp
 *
 *  @date 19-nov-2009
 *  @author Ives van der Flaas
 */

#include <iostream>
#include <SDL_framerate.h>
#include "SDLApplication.h"
#include "SDLWindow.h"
#include "SDLTimer.h"
#include "SDLSplashSection.h"
#include "SDLIntroSection.h"
#include "SDLMenuSection.h"
#include "SDLGameSection.h"
#include "SDLLostSection.h"
#include "SDLHighScoreSection.h"
#include "notYetImplementedException.h"


si_sdl::SDLApplication::SDLApplication():
	Application(new SDLWindow("Earth Protector 0.1.0"))
{
	fSplashSection = new SDLSplashSection(
						*this,
						*dynamic_cast<SDLWindow*>(fWindow));

	fIntroSection = new SDLIntroSection(
						*this,
						*dynamic_cast<SDLWindow*>(fWindow));

	fMenuSection = new SDLMenuSection(
						*this,
						*dynamic_cast<SDLWindow*>(fWindow));

	fGameSection = new SDLGameSection(
						*this,
						*dynamic_cast<SDLWindow*>(fWindow));


	fLostSection = new SDLLostSection(
						*this,
						*dynamic_cast<SDLWindow*>(fWindow));

	fHighScoresSection = new SDLHighScoreSection(
						*this,
						*dynamic_cast<SDLWindow*>(fWindow));

	fCurrentAppSection = fSplashSection;
}

si_sdl::SDLApplication::~SDLApplication()
{
	delete fWindow;

	delete fSplashSection;
	delete fIntroSection;
	delete fMenuSection;
	delete fGameSection;
	delete fLostSection;
	delete fHighScoresSection;

}

void si_sdl::SDLApplication::loop()
{
    si_sdl::SDLTimer timer;

    FPSmanager mgr;
    SDL_initFramerate(&mgr);
    // set framerate to 60 fps
    const int frameRate = 40;
    SDL_setFramerate(&mgr, frameRate);

    while(!fCurrentAppSection->wantsAppExit())
    {
		SDL_framerateDelay(&mgr);

    	SDLApplicationSection* appSec = dynamic_cast<SDLApplicationSection*>
											(fCurrentAppSection);



    	if(appSec == 0)
    	{
    		throw SDLException("Cannot cast current appsection to SDLAppsection."
    				"This is really serious.");
    	}

    	SDL_Event event;
        while(SDL_PollEvent(&event))
			appSec->onSDLEvent(event);


		const double timePassed = timer.reset();
        appSec->newFrame(timePassed);
		dynamic_cast<SDLWindow*>(fWindow)->flip();


    }

}











